package com.awangyh.jdk8.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by admin on 2017/4/12.
 */
public class ThreadLocalDemo {

    public static ThreadLocal<List<String>> local = new ThreadLocal<>();

    public List<String> get() {
        return local.get();
    }

    public void add(String item) {
        if ( local.get() == null) {
            local.set(new ArrayList<>());
        }

        local.get().add(item);

    }

    private void modify() throws InterruptedException {
        ExecutorService executor = Executors.newWorkStealingPool();
        for ( int i = 0 ; i < 20; i++) {
            executor.submit(() -> add(UUID.randomUUID().toString()));
        }


        executor.shutdown();
        executor.awaitTermination(3, TimeUnit.SECONDS);
        add("all");
    }


    public static void main(String[] args) {
        ThreadLocalDemo demo = new ThreadLocalDemo();
        try {
            demo.modify();

            demo.get().forEach(it -> System.out.println(it));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
